<!-- 在线导出弹窗（支持填写任务名称和选择导出目录） -->
<template>
  <modal-form
    :form-state="formState"
    :show="show"
    title="在线导出"
    width="600px"
    :rules="modelFormRules"
    :loading="loading"
    @cancel="onCancel"
    @ok="onOk"
  >
    <template #default="{ formState }" v-if="show">
      <a-form-item label="任务名称" name="name">
        <a-input v-model:value="formState.name" v-trim style="width: 328px" placeholder="请输入任务名称" :maxlength="200" />
      </a-form-item>
      <a-form-item name="value">
        <radio-tree-data ref="mainModuleRef" v-model:value="formState.value" type="data" />
      </a-form-item>
    </template>
  </modal-form>
</template>

<script setup lang="ts">
  import type { Rule } from 'ant-design-vue/es/form'
  import { reactive, ref, watch } from 'vue'
  import { nextTick } from 'vue'
  import { onUnmounted } from 'vue'

  import { validateBitLen, validateDirName } from '@/utils'

  interface LineExportProps {
    show: boolean
    loading?: boolean
  }

  const props = withDefaults(defineProps<LineExportProps>(), {
    show: false
  })

  const emits = defineEmits<{
    (e: 'update:show', value: boolean): void
    (e: 'submit', formState: FormStateType): void
  }>()

  const mainModuleRef = ref()

  const formState = reactive({
    name: '',
    value: ''
  })

  type FormStateType = typeof formState

  const modelFormRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入任务名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ],
    value: [{ required: true, trigger: 'change', message: '请选择数据集' }]
  }

  const open = async () => {
    emits('update:show', true)
    await nextTick()
    mainModuleRef.value?.getTreeData()
  }

  const onOk = () => {
    emits('submit', formState)
  }

  const onCancel = () => {
    Object.assign(formState, {
      name: '',
      value: ''
    })
    mainModuleRef.value?.clearBread()
    mainModuleRef.value?.setSearchValue()
    emits('update:show', false)
  }

  const setFormState = (state: Partial<FormStateType>) => {
    Object.assign(formState, state)
  }

  const stopWatch = watch(
    () => props.show,
    val => {
      if (val) {
        open()
      } else {
        onCancel()
      }
    }
  )

  onUnmounted(() => {
    stopWatch()
  })

  defineExpose({
    setFormState
  })
</script>
